<?php
/**
 * User: @lose
 * Date: 2020/10/20
 * Time: 10:47 上午
 */

namespace Frieza\Modules\Activity\Controllers;

use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\tools\IdGen;
use Doraemon\tools\IdParse;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use Encore\Admin\Grid;
use Illuminate\Http\Request;
use Doraemon\service\WeeklyList as sWeeklyList;
use Doraemon\cache\WeeklyList as cWeeklyList;

class WeeklyListController
{
    public function guide(Content $content)
    {
        $list = [];
        foreach (sWeeklyList::FEATURE_LIST as $key => $value) {
            $list[] = [
                'id' => $key,
                'value' => $value
            ];
        }

        $gridModel = new pGridDataModel($list);

        $grid = Admin::grid($gridModel,
            function (Grid $grid) {
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableFilter();
                $grid->disableCreateButton();
                $grid->disablePagination();
                $grid->column('value', '题材')->display(function () {
                    return "<a href='/admin/activity/weeklyList/".$this->id."' target='_blank'>$this->value</a>";
                });
                $grid->tools(function (Grid\Tools $tool) use ($grid) {
                    $tool->append("<a href='weeklyListExport' target='_blank' class='btn btn-sm btn-success' style='float: right;margin-left:5px;'>
<i class='fa fa-cloud-download'>&nbsp;&nbsp;导出uid</i></a>");
                });
                $grid->disableActions();
            }
        );

        return $content
            ->header('住友周榜')
            ->breadcrumb(['text' => '住友周榜题材'])
            ->row($grid);
    }

    public function index(Content $content, $featureId = sWeeklyList::CONSTRUCTION_DRY_GOODS)
    {
        $list = sWeeklyList::getListByAdmin($featureId);
        return $content
            ->header(sWeeklyList::FEATURE_LIST[$featureId])
            ->breadcrumb(['text' => '住友周榜题材', 'url' => 'activity/weeklyList'], ['text' => sWeeklyList::FEATURE_LIST[$featureId]])
            ->row($this->_formatGrid($featureId, $list));
    }

    private function _formatGrid($featureId, $list)
    {
        $gridModel = new pGridDataModel($list['list'], $list['total'], [
            'keyName' => 'uid'
        ]);

        $grid = Admin::grid($gridModel,
            function (Grid $grid) use ($featureId) {
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disablePagination();
                $grid->disableCreateButton();
                $grid->disableFilter();
                for ($i=1;$i<=10;$i++) {
                    $rank[$i] = $i;
                }
                $grid->quickCreate(function (Grid\Tools\QuickCreate $create) use ($featureId, $rank) {
                    $create->text('uid', '用户id')->required();
                    $create->text('obj_id', '内容id')->required();
                    $create->select('rank', '排名')->options($rank)->required();
                    $create->text('feature_id')->default($featureId)->readonly();
                });

                $grid->column('ori_rank', '内容排名')->display(function () {
                    return $this->ori_rank == 0 ? '运营手动配置' : $this->ori_rank;
                });
                $grid->column('uid', '用户信息')->userBasicInfo()->width(150);
                $grid->column('obj_id', '内容id')->link(function () {
                    return '/admin/photo/photoList/index?show_type=1&is_consume=2&note_id=' . $this->obj_id ;
                });
                $grid->column('interactive', '交互量');
                $grid->column('tag', '标签')->label(
                    [
                        1 => 'warning',
                        2 => 'warning',
                        3 => 'info'
                    ]
                );

//                $array = range(1,10);
//                // 排名是从1开始。range生成的数组下标是从0开始。
//                // editable的组件是按照key取数据的，所以第一名会显示成第二名。
//                // 这个地方为了处理这个问题，将key+1
//                foreach ($array as $key => $value) {
//                    $rank[$key + 1] = $value;
//                }

                if(date('w') != 1 || date('H') >= 20) {
                    $grid->column('rank', '活动排名')->display(function () {
                        return $this->rank == 99 ? '未上榜' : $this->rank;
                    });
                } else {
                    $grid->column('rank', '活动排名')->editable('select', $rank + [sWeeklyList::DEFAULT_RANK => '不上榜'])->help('默认为不上榜.选择排名后就会上榜.上榜后选择「不上榜」即可从榜单移除该用户');
                }

                $grid->disableActions();
            }
        );

        return $grid;
    }

    public function check(Request $request, $featureId)
    {
        $name = $request->input('name', '');
        $mark = $request->input('pk');
        $value = $request->input('value');

        try {
            // 基于 $featureId 修改制定数据的cache
            // redis hash key:check_time  field:feature value:data
            if($name == 'rank') {
                if(date('w') != 1 || date('H') >= 20) {
                    throw new \Exception('只有周一8点前可以设置');
                }

                sWeeklyList::setWeeklyList($featureId, $mark, $value);

            }

            return response()->json([
                'status' => true,
                'message' => '操作成功',
            ]);
        } catch (\Exception $e) {
            return response()->json(['errors' => [$message = $e->getMessage()]], 422);
        }
    }

    public function add(Request $request)
    {
        try {
            if(date('w') != 1 || date('H') >= 20) {
                throw new \Exception('只有周一8点前可以设置');
            }
            $uid = $request->get('uid');
            $objId = $request->get('obj_id');
            $rank = $request->get('rank');
            $featureId = $request->get('feature_id');
            $authorUid = IdParse::getUidFromObjId($objId);
            $objType = IdParse::getType($objId);
            if ($objType != IdGen::TYPE_PHOTO) {
                throw new \Exception('必须为note_id');
            }

            // 通过这种方式验证用户id及内容id是否正确
            if ($uid != $authorUid) {
                throw new \Exception('uid或内容id异常');
            }

            sWeeklyList::setWeeklyList($featureId, $uid, $rank, $objId);

            return response()->json([
                'status' => true,
                'message' => '保存成功',
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => false,
                'message' => $e->getMessage(),
            ], 422);
        }
    }

    public function export()
    {
        $date = date('Ymd');
        $key = cWeeklyList::CHECK_DATA . $date;
        $list = cWeeklyList::getALL($key); // 查询本周上榜的内容
        foreach ($list as $featureId => $info) {
            if($info) {
                foreach ($info as $item) {
                    echo $item['uid'] . '<br/>';
                    echo PHP_EOL;
                }
            }
        }
        die;
    }
}